package netssl;

import javax.swing.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigInteger;
import java.security.*;
import java.security.cert.CertificateException;
import java.util.Enumeration;

public class J_ShowKeystore {

    public static void main(String[] args) {
        System.out.println(System.getProperty("user.home"));

        String ks_name;
        if (args.length<1){
            ks_name = System.getProperty("user.home")+"\\.keystore";
        }else {
            ks_name = args[0];
        }
        try {
            FileInputStream fis = new FileInputStream(ks_name);
            KeyStore ks = KeyStore.getInstance("JKS");
            String password = "123456";//密钥库密码
            String epw = "123456";//密钥项密码
            String a;//密钥项别名
            PrivateKey pk;//密钥项私钥
            byte[] k;
            if (args.length>1){
                password = args[1]; //由程序参数指定密钥库密码
                System.out.println("password:"+password);
            }
            ks.load(fis,password.toCharArray());
            //获取并显示在密钥库中的密钥项别名
            Enumeration<String> e = ks.aliases();//获取各个密钥项别名
            while (e.hasMoreElements()){
                a = e.nextElement();//取出密钥项别名
                System.out.println("密钥项"+a+"的私钥是：");
                pk = (PrivateKey)ks.getKey(a,epw.toCharArray()); //获取密钥项私钥
                k = pk.getEncoded();
                System.out.println((new BigInteger(k)).toString(16));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (CertificateException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            e.printStackTrace();
        }
    }

}
